package zy.service.sort.allot.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import zy.dao.approve.ApproveRecordDAO;
import zy.dao.base.product.ProductDAO;
import zy.dao.base.shop.ShopDAO;
import zy.dao.base.size.SizeDAO;
import zy.dao.sort.allot.AllotDAO;
import zy.dao.sort.dealings.SortDealingsDAO;
import zy.dao.stock.data.DataDAO;
import zy.dao.stock.useable.UseableDAO;
import zy.dao.sys.print.PrintDAO;
import zy.dto.common.BarcodeImportDto;
import zy.dto.common.ProductDto;
import zy.dto.shop.want.ProductStorePriceDto;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.approve.T_Approve_Record;
import zy.entity.base.product.T_Base_Barcode;
import zy.entity.base.product.T_Base_Product;
import zy.entity.base.product.T_Base_Product_Shop_Price;
import zy.entity.base.shop.T_Base_Shop;
import zy.entity.base.size.T_Base_Size;
import zy.entity.base.size.T_Base_SizeList;
import zy.entity.sort.allot.T_Sort_Allot;
import zy.entity.sort.allot.T_Sort_AllotList;
import zy.entity.sort.dealings.T_Sort_Dealings;
import zy.entity.stock.data.T_Stock_DataBill;
import zy.entity.sys.set.T_Sys_Set;
import zy.entity.sys.user.T_Sys_User;
import zy.service.sort.allot.AllotService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.StringUtil;
import zy.vo.common.SizeHorizontalVO;
import zy.vo.sort.AllotVO;

@Service
public class AllotServiceImpl implements AllotService{
	@Resource
	private AllotDAO allotDAO;
	
	@Resource
	private SizeDAO sizeDAO;
	
	@Resource
	private ApproveRecordDAO approveRecordDAO;
	
	@Resource
	private DataDAO dataDAO;
	
	@Resource
	private SortDealingsDAO sortDealingsDAO;
	
	@Resource
	private PrintDAO printDAO;
	
	@Resource
	private ShopDAO shopDAO;
	
	@Resource
	private UseableDAO useableDAO;
	
	@Resource
	private ProductDAO productDAO;

	@Override
	public PageData<T_Sort_Allot> page(Map<String, Object> params) {
		Object companyid = params.get(CommonUtil.COMPANYID);
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Map<String, Object> sumMap = allotDAO.countSum(params);
		int totalCount = Integer.parseInt(sumMap.get("totalCount").toString());
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<T_Sort_Allot> list = allotDAO.list(params);
		PageData<T_Sort_Allot> pageData = new PageData<T_Sort_Allot>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		pageData.setData(sumMap);
		return pageData;
	}
	
	@Override
	public List<T_Sort_Allot> listExport(Map<String, Object> params) {
		Assert.notNull(params.get(CommonUtil.COMPANYID),"连接超时，请重新登录!");
		params.put(CommonUtil.START, 0);
		params.put(CommonUtil.END, Integer.MAX_VALUE);
		return allotDAO.list(params);
	}
	
	@Override
	public T_Sort_Allot load(Integer at_id) {
		T_Sort_Allot allot = allotDAO.load(at_id);
		if(allot != null){
			T_Approve_Record approve_Record = approveRecordDAO.load(allot.getAt_number(), allot.getCompanyid());
			if(approve_Record != null){
				allot.setAr_describe(approve_Record.getAr_describe());
			}
		}
		return allot;
	}
	
	@Override
	public T_Sort_Allot load(String number, Integer companyid) {
		return allotDAO.load(number,companyid);
	}
	
	@Override
	public List<T_Sort_AllotList> detail_list(Map<String, Object> params) {
		return allotDAO.detail_list(params);
	}
	
	@Override
	public List<T_Sort_AllotList> detail_sum(Map<String, Object> params) {
		return allotDAO.detail_sum(params);
	}
	
	@Override
	public Map<String, Object> detail_size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = allotDAO.detail_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("titles", new ArrayList<List<String>>());
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		return SizeHorizontalVO.getJsonSizeTitles(sizeGroupList);
	}
	
	@Override
	public Map<String, Object> detail_size(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		Integer at_ar_state = (Integer)params.get("at_ar_state");
		Integer isFHD = (Integer)params.get("isFHD");
		Integer isSend = (Integer)params.get("isSend");
		List<String> szgCodes = allotDAO.detail_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return new HashMap<String, Object>();
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		params.put(CommonUtil.SIDX, "atl_pd_code,atl_cr_code,atl_br_code");
		params.put(CommonUtil.SORD, "ASC");
		List<T_Sort_AllotList> temps = allotDAO.detail_list(params);
		boolean sendAmount = false;//尺码横排是否使用发货数量
		if(isSend.intValue() == 1){
			sendAmount = true;
		}else if(isFHD.intValue() == 1){
			sendAmount = true;
		}else if(at_ar_state.intValue() == 3 || at_ar_state.intValue() == 4 || at_ar_state.intValue() == 5){
			sendAmount = true;
		}
		return AllotVO.getJsonSizeData(sizeGroupList, temps,sendAmount);
	}
	
	@Override
	public List<T_Sort_AllotList> temp_list(Map<String, Object> params) {
		return allotDAO.temp_list(params);
	}

	@Override
	public List<T_Sort_AllotList> temp_sum(Integer at_type,Integer atl_up, Integer us_id,Integer companyid) {
		return allotDAO.temp_sum(at_type,atl_up, us_id, companyid);
	}

	@Override
	public Map<String, Object> temp_size_title(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = allotDAO.temp_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("titles", new ArrayList<List<String>>());
			return resultMap;
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		return SizeHorizontalVO.getJsonSizeTitles(sizeGroupList);
	}

	@Override
	public Map<String, Object> temp_size(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		List<String> szgCodes = allotDAO.temp_szgcode(params);
		if(szgCodes==null||szgCodes.size()==0){
			return new HashMap<String, Object>();
		}
		List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, companyid);
		params.put(CommonUtil.SIDX, "atl_pd_code,atl_cr_code,atl_br_code");
		params.put(CommonUtil.SORD, "ASC");
		List<T_Sort_AllotList> temps = allotDAO.temp_list(params);
		return AllotVO.getJsonSizeData(sizeGroupList, temps,false);
	}
	
	@Override
	public PageData<T_Base_Product> page_product(Map<String, Object> param) {
		Object companyid = param.get(CommonUtil.COMPANYID);
		Object pageSize = param.get(CommonUtil.PAGESIZE);
		Object pageIndex = param.get(CommonUtil.PAGEINDEX);
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = allotDAO.count_product(param);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		param.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		param.put(CommonUtil.END, _pageSize);
		
		List<T_Base_Product> list = allotDAO.list_product(param);
		PageData<T_Base_Product> pageData = new PageData<T_Base_Product>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> temp_loadproduct(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		T_Sys_Set sysSet = (T_Sys_Set)params.get(CommonUtil.KEY_SYSSET);
		Integer us_id = (Integer)params.get("us_id");
		String pd_code = (String)params.get("pd_code");
		String dp_code = (String)params.get("dp_code");
		String sp_code = (String)params.get("sp_code");
		String priceType = (String)params.get("priceType");
		Double sp_rate = (Double)params.get("sp_rate");
		Integer at_type = (Integer)params.get("at_type");
		Integer atl_up = (Integer)params.get("atl_up");
		String exist = (String)params.get("exist");
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		T_Base_Product base_Product = allotDAO.load_product(pd_code,sp_code, companyid);
		Map<String, Object> product = new HashMap<String, Object>();
		product.put("pd_id", base_Product.getPd_id());
		product.put("pd_code", base_Product.getPd_code());
		product.put("pd_no", base_Product.getPd_no());
		product.put("pd_name", base_Product.getPd_name());
		product.put("pd_szg_code", base_Product.getPd_szg_code());
		product.put("pd_unit", base_Product.getPd_unit());
		product.put("pd_year", base_Product.getPd_year());
		product.put("pd_season", base_Product.getPd_season());
		product.put("pd_sell_price", base_Product.getPd_sell_price());
		product.put("pd_cost_price", base_Product.getPd_cost_price());
		product.put("pd_sort_price", base_Product.getPd_sort_price());
		product.put("pd_bd_name", base_Product.getPd_bd_name());
		product.put("pd_tp_name", base_Product.getPd_tp_name());
		product.put("pdm_img_path", StringUtil.trimString(base_Product.getPdm_img_path()));
		Double unitPrice = null;
		if("1".equals(exist)){//已经录入从临时表中查询单价
			T_Sort_AllotList temp_price = allotDAO.temp_queryUnitPrice(pd_code, at_type,atl_up, us_id, companyid);
			if (temp_price != null) {
				unitPrice = temp_price.getAtl_unitprice();
				product.put("temp_unitPrice", StringUtil.trimString(unitPrice));
			}
		}
		if(unitPrice == null){
			if("1".equals(priceType)){//最近配送价
				unitPrice = base_Product.getPd_sort_price();
			}else if("2".equals(priceType)){//按照折扣率
				unitPrice = base_Product.getPd_sell_price() * sp_rate;
			}
		}
		product.put("unitPrice", unitPrice);
		resultMap.put("product", product);
		params.put("szg_code", base_Product.getPd_szg_code());
		Map<String, Object> productMap = allotDAO.load_product_size(params);
		List<T_Base_Size> sizes=(List<T_Base_Size>)productMap.get("sizes");
		List<ProductDto> inputs=(List<ProductDto>)productMap.get("inputs");
		List<ProductDto> temps=(List<ProductDto>)productMap.get("temps");
		List<ProductDto> stocks=(List<ProductDto>)productMap.get("stocks");
		Map<String,Object> usableStockMap = null;
		if (sysSet.getSt_useable() != null && sysSet.getSt_useable().intValue() == 1) {
			usableStockMap = useableDAO.loadUseableStock(pd_code, dp_code, companyid);
		}
		resultMap.putAll(SizeHorizontalVO.buildJsonProductInput(pd_code, sizes, inputs, stocks, temps, usableStockMap));
		return resultMap;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> send_loadproduct(Map<String, Object> params) {
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		T_Sys_Set sysSet = (T_Sys_Set)params.get(CommonUtil.KEY_SYSSET);
		String at_number = (String)params.get("at_number");
		String pd_code = (String)params.get("pd_code");
		String dp_code = (String)params.get("dp_code");
		String sp_code = (String)params.get("sp_code");
		String priceType = (String)params.get("priceType");
		Double sp_rate = (Double)params.get("sp_rate");
		String exist = (String)params.get("exist");
		if (companyid == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		T_Base_Product base_Product = allotDAO.load_product(pd_code,sp_code, companyid);
		Map<String, Object> product = new HashMap<String, Object>();
		product.put("pd_id", base_Product.getPd_id());
		product.put("pd_code", base_Product.getPd_code());
		product.put("pd_no", base_Product.getPd_no());
		product.put("pd_name", base_Product.getPd_name());
		product.put("pd_szg_code", base_Product.getPd_szg_code());
		product.put("pd_unit", base_Product.getPd_unit());
		product.put("pd_year", base_Product.getPd_year());
		product.put("pd_season", base_Product.getPd_season());
		product.put("pd_sell_price", base_Product.getPd_sell_price());
		product.put("pd_cost_price", base_Product.getPd_cost_price());
		product.put("pd_sort_price", base_Product.getPd_sort_price());
		product.put("pd_bd_name", base_Product.getPd_bd_name());
		product.put("pd_tp_name", base_Product.getPd_tp_name());
		product.put("pdm_img_path", StringUtil.trimString(base_Product.getPdm_img_path()));
		Double unitPrice = null;
		if("1".equals(exist)){//已经录入从临时表中查询单价
			T_Sort_AllotList temp_price = allotDAO.detail_queryUnitPrice(pd_code, at_number, companyid);
			if (temp_price != null) {
				unitPrice = temp_price.getAtl_unitprice();
				product.put("temp_unitPrice", StringUtil.trimString(unitPrice));
			}
		}
		if(unitPrice == null){
			if("1".equals(priceType)){//最近批发价
				unitPrice = base_Product.getPd_sort_price();
			}else if("2".equals(priceType)){//按照折扣率
				unitPrice = base_Product.getPd_sell_price() * sp_rate;
			}
		}
		product.put("unitPrice", unitPrice);
		resultMap.put("product", product);
		params.put("szg_code", base_Product.getPd_szg_code());
		Map<String, Object> productMap = allotDAO.load_product_size_send(params);
		List<T_Base_Size> sizes=(List<T_Base_Size>)productMap.get("sizes");
		List<ProductDto> inputs=(List<ProductDto>)productMap.get("inputs");
		List<ProductDto> temps=(List<ProductDto>)productMap.get("temps");
		List<ProductDto> stocks=(List<ProductDto>)productMap.get("stocks");
		Map<String,Object> usableStockMap = null;
		if (sysSet.getSt_useable() != null && sysSet.getSt_useable().intValue() == 1) {
			usableStockMap = useableDAO.loadUseableStock(pd_code, dp_code, companyid);
		}
		resultMap.putAll(SizeHorizontalVO.buildJsonProductInput(pd_code, sizes, inputs, stocks, temps, usableStockMap));
		return resultMap;
	}
	
	@Override
	@Transactional
	public Map<String, Object> temp_save_bybarcode(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Integer at_type = (Integer)params.get("at_type");
		Integer atl_up = (Integer)params.get("atl_up");
		String barcode = (String)params.get("barcode");
		Integer amount = (Integer)params.get("amount");
		String sp_code = (String)params.get("sp_code");
		String priceType = (String)params.get("priceType");
		Double sp_rate = (Double)params.get("sp_rate");
		T_Sys_User user = (T_Sys_User)params.get("user");
		T_Base_Barcode base_Barcode = productDAO.loadBarcode(barcode, user.getCompanyid());
		if(base_Barcode == null){
			resultMap.put("result", 3);//条码不存在
			return resultMap;
		}
		T_Sort_AllotList temp = allotDAO.temp_loadBySubCode(base_Barcode.getBc_subcode(), at_type,atl_up, user.getUs_id(), user.getCompanyid());
		if (temp != null) {//临时表存在则直接更新数量
			temp.setAtl_applyamount(temp.getAtl_applyamount()+amount);
			allotDAO.temp_update(temp);
			resultMap.put("result", 1);//update
			resultMap.put("temp", temp);
			return resultMap;
		}
		T_Base_Product base_Product = allotDAO.load_product(base_Barcode.getBc_pd_code(),sp_code, user.getCompanyid());
		T_Sort_AllotList temp_price= allotDAO.temp_queryUnitPrice(base_Barcode.getBc_pd_code(),at_type,atl_up, user.getUs_id(), user.getCompanyid());;
		Double unitPrice = null;
		if(temp_price != null){
			unitPrice = temp_price.getAtl_unitprice();
		}else {
			if("1".equals(priceType)){//最近批发价
				unitPrice = base_Product.getPd_sort_price();
			}else if("2".equals(priceType)){//按照折扣率
				unitPrice = base_Product.getPd_sell_price() * sp_rate;
			}
		}
		
		temp = new T_Sort_AllotList();
		temp.setAtl_pd_code(base_Barcode.getBc_pd_code());
		temp.setAtl_cr_code(base_Barcode.getBc_color());
		temp.setAtl_sz_code(base_Barcode.getBc_size());
		temp.setAtl_szg_code(base_Product.getPd_szg_code());
		temp.setAtl_br_code(base_Barcode.getBc_bra());
		temp.setAtl_sub_code(temp.getAtl_pd_code()+temp.getAtl_cr_code()+temp.getAtl_sz_code()+temp.getAtl_br_code());
		temp.setAtl_applyamount(amount);
		temp.setAtl_unitprice(unitPrice);
		temp.setAtl_sellprice(base_Product.getPd_sell_price());
		temp.setAtl_costprice(base_Product.getPd_cost_price());
		temp.setAtl_remark("");
		temp.setAtl_type(at_type);
		temp.setAtl_up(atl_up);
		temp.setAtl_us_id(user.getUs_id());
		temp.setCompanyid(user.getCompanyid());
		allotDAO.temp_save(temp);
		temp.setPd_no(base_Product.getPd_no());
		temp.setPd_name(base_Product.getPd_name());
		temp.setPd_unit(base_Product.getPd_unit());
		temp.setBd_name(base_Product.getPd_bd_name());
		temp.setTp_name(base_Product.getPd_tp_name());
		temp.setCr_name(base_Barcode.getBc_colorname());
		temp.setSz_name(base_Barcode.getBc_sizename());
		temp.setBr_name(base_Barcode.getBc_braname());
		resultMap.put("result", 2);//add
		resultMap.put("temp", temp);
		return resultMap;
	}
	
	@Override
	@Transactional
	public Map<String, Object> detail_save_bybarcode(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Integer at_type = (Integer)params.get("at_type");
		String at_number = (String)params.get("at_number");
		String barcode = (String)params.get("barcode");
		Integer amount = (Integer)params.get("amount");
		String sp_code = (String)params.get("sp_code");
		String priceType = (String)params.get("priceType");
		Double sp_rate = (Double)params.get("sp_rate");
		T_Sys_User user = (T_Sys_User)params.get("user");
		T_Base_Barcode base_Barcode = productDAO.loadBarcode(barcode, user.getCompanyid());
		if(base_Barcode == null){
			resultMap.put("result", 3);//条码不存在
			return resultMap;
		}
		T_Sort_AllotList temp = allotDAO.detail_loadBySubCode(base_Barcode.getBc_subcode(),at_number, user.getCompanyid());
		if (temp != null) {//临时表存在则直接更新数量
			if (at_type.intValue() == 0) {
				temp.setAtl_sendamount(temp.getAtl_sendamount() + amount);
			} else {
				temp.setAtl_sendamount(temp.getAtl_sendamount() - amount);
			}
			allotDAO.detail_update(temp);
			resultMap.put("result", 1);//update
			resultMap.put("temp", temp);
			return resultMap;
		}
		T_Base_Product base_Product = allotDAO.load_product(base_Barcode.getBc_pd_code(),sp_code, user.getCompanyid());
		T_Sort_AllotList temp_price= allotDAO.detail_queryUnitPrice(base_Barcode.getBc_pd_code(),at_number, user.getCompanyid());;
		Double unitPrice = null;
		if(temp_price != null){
			unitPrice = temp_price.getAtl_unitprice();
		}else {
			if("1".equals(priceType)){//最近批发价
				unitPrice = base_Product.getPd_sort_price();
			}else if("2".equals(priceType)){//按照折扣率
				unitPrice = base_Product.getPd_sell_price() * sp_rate;
			}
		}
		temp = new T_Sort_AllotList();
		temp.setAtl_number(at_number);
		temp.setAtl_pd_code(base_Barcode.getBc_pd_code());
		temp.setAtl_cr_code(base_Barcode.getBc_color());
		temp.setAtl_sz_code(base_Barcode.getBc_size());
		temp.setAtl_szg_code(base_Product.getPd_szg_code());
		temp.setAtl_br_code(base_Barcode.getBc_bra());
		temp.setAtl_sub_code(temp.getAtl_pd_code()+temp.getAtl_cr_code()+temp.getAtl_sz_code()+temp.getAtl_br_code());
		temp.setAtl_applyamount(0);
		if (at_type.intValue() == 0) {
			temp.setAtl_sendamount(amount);
		} else {
			temp.setAtl_sendamount(-amount);
		}
		temp.setAtl_unitprice(unitPrice);
		temp.setAtl_sellprice(base_Product.getPd_sell_price());
		temp.setAtl_costprice(base_Product.getPd_cost_price());
		temp.setAtl_remark("");
		temp.setAtl_type(at_type);
		temp.setAtl_us_id(user.getUs_id());
		temp.setCompanyid(user.getCompanyid());
		allotDAO.detail_save(temp);
		temp.setPd_no(base_Product.getPd_no());
		temp.setPd_name(base_Product.getPd_name());
		temp.setPd_unit(base_Product.getPd_unit());
		temp.setBd_name(base_Product.getPd_bd_name());
		temp.setTp_name(base_Product.getPd_tp_name());
		temp.setCr_name(base_Barcode.getBc_colorname());
		temp.setSz_name(base_Barcode.getBc_sizename());
		temp.setBr_name(base_Barcode.getBc_braname());
		resultMap.put("result", 2);//add
		resultMap.put("temp", temp);
		return resultMap;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public void temp_save(Map<String, Object> params) {
		List<T_Sort_AllotList> temps = (List<T_Sort_AllotList>)params.get("temps");
		Integer at_type = (Integer)params.get("at_type");
		Integer atl_up = (Integer)params.get("atl_up");
		T_Sys_User user = (T_Sys_User)params.get("user");
		Object pd_code = params.get("pd_code");
		Object unitPrice = params.get("unitPrice");
		if (temps != null && temps.size() > 0) {
			List<T_Sort_AllotList> temps_add = new ArrayList<T_Sort_AllotList>();
			List<T_Sort_AllotList> temps_update = new ArrayList<T_Sort_AllotList>();
			List<T_Sort_AllotList> temps_del = new ArrayList<T_Sort_AllotList>();
			for (T_Sort_AllotList item : temps) {
				if ("add".equals(item.getOperate_type())){
					if (item.getAtl_applyamount() > 0) {
						temps_add.add(item);
					}
				}else if("update".equals(item.getOperate_type())){
					if(!item.getAtl_applyamount().equals(0)){
						temps_update.add(item);
					}else {
						temps_del.add(item);
					}
				}
			}
			if (temps_add.size() > 0) {
				allotDAO.temp_save(temps_add);
			}
			if (temps_update.size() > 0) {
				allotDAO.temp_update(temps_update);
			}
			if (temps_del.size() > 0) {
				allotDAO.temp_del(temps_del);
			}
		}
		if (StringUtil.isNotEmpty(pd_code) && StringUtil.isNotEmpty(unitPrice)) {
			allotDAO.temp_updateprice(pd_code.toString(),Double.parseDouble(unitPrice.toString()), at_type,atl_up, user.getUs_id(), user.getCompanyid());
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public void send_save_detail(Map<String, Object> params) {
		List<T_Sort_AllotList> temps = (List<T_Sort_AllotList>)params.get("temps");
		String at_number = (String)params.get("at_number");
		T_Sys_User user = (T_Sys_User)params.get("user");
		Object pd_code = params.get("pd_code");
		Object unitPrice = params.get("unitPrice");
		if (temps != null && temps.size() > 0) {
			List<T_Sort_AllotList> temps_add = new ArrayList<T_Sort_AllotList>();
			List<T_Sort_AllotList> temps_update = new ArrayList<T_Sort_AllotList>();
			List<T_Sort_AllotList> temps_del = new ArrayList<T_Sort_AllotList>();
			for (T_Sort_AllotList item : temps) {
				if ("add".equals(item.getOperate_type())){
					if (item.getAtl_sendamount() > 0) {
						temps_add.add(item);
					}
				}else if("update".equals(item.getOperate_type())){
					if(!item.getAtl_sendamount().equals(0)){
						temps_update.add(item);
					}else {
						temps_del.add(item);
					}
				}
			}
			if (temps_add.size() > 0) {
				allotDAO.detail_save(temps_add);
			}
			if (temps_update.size() > 0) {
				allotDAO.detail_update(temps_update);
			}
			if (temps_del.size() > 0) {
				allotDAO.detail_del(temps_del);
			}
		}
		if (StringUtil.isNotEmpty(pd_code) && StringUtil.isNotEmpty(unitPrice)) {
			allotDAO.detail_updateprice(pd_code.toString(),Double.parseDouble(unitPrice.toString()), at_number, user.getCompanyid());
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public void temp_import(Map<String, Object> params) {
		List<String[]> datas = (List<String[]>)params.get("datas");
		Integer at_type = (Integer)params.get("at_type");
		Integer atl_up = (Integer)params.get("atl_up");
		T_Sys_User user = (T_Sys_User)params.get("user");
		String sp_code = (String)params.get("sp_code");
		String priceType = (String)params.get("priceType");
		Double sp_rate = Double.parseDouble(params.get("sp_rate").toString());
		List<String> barcodes = new ArrayList<String>();
		Map<String, Integer> data_amount = new HashMap<String, Integer>();
		for (String[] data : datas) {
			barcodes.add(data[0]);
			data_amount.put(data[0], Integer.parseInt(data[1]));
		}
		List<BarcodeImportDto> imports = allotDAO.temp_listByImport(barcodes, priceType, sp_rate, sp_code, user.getCompanyid());
		if (imports == null || imports.size() == 0) {
			throw new RuntimeException("无数据可导入");
		}
		Map<String, Double> unitPriceMap = new HashMap<String, Double>();
		Map<String, T_Sort_AllotList> tempsMap = new HashMap<String, T_Sort_AllotList>();
		List<T_Sort_AllotList> temps = allotDAO.temp_list_forimport(at_type,atl_up, user.getUs_id(), user.getCompanyid());
		for (T_Sort_AllotList temp : temps) {
			if(!unitPriceMap.containsKey(temp.getAtl_pd_code())){
				unitPriceMap.put(temp.getAtl_pd_code(), temp.getAtl_unitprice());
			}
			tempsMap.put(temp.getAtl_sub_code(), temp);
		}
		List<T_Sort_AllotList> temps_add = new ArrayList<T_Sort_AllotList>();
		List<T_Sort_AllotList> temps_update = new ArrayList<T_Sort_AllotList>();
		for (BarcodeImportDto item : imports) {
			if(tempsMap.containsKey(item.getBc_subcode())){//临时表已存在，更新数量
				T_Sort_AllotList temp = tempsMap.get(item.getBc_subcode());
				temp.setAtl_applyamount(temp.getAtl_applyamount()+data_amount.get(item.getBc_barcode()));
				temps_update.add(temp);
			}else {//临时表不存在，新增数据
				T_Sort_AllotList temp = new T_Sort_AllotList();
				temp.setAtl_pd_code(item.getBc_pd_code());
				temp.setAtl_sub_code(item.getBc_subcode());
				temp.setAtl_sz_code(item.getBc_size());
				temp.setAtl_szg_code(item.getPd_szg_code());
				temp.setAtl_cr_code(item.getBc_color());
				temp.setAtl_br_code(item.getBc_bra());
				temp.setAtl_applyamount(data_amount.get(item.getBc_barcode()));
				if(unitPriceMap.containsKey(item.getBc_pd_code())){//临时表已存在此货号，则使用临时表价格
					temp.setAtl_unitprice(unitPriceMap.get(item.getBc_pd_code()));
				}else {
					temp.setAtl_unitprice(item.getUnit_price());
				}
				temp.setAtl_sellprice(item.getSell_price());
				temp.setAtl_costprice(item.getCost_price());
				temp.setAtl_remark("");
				temp.setAtl_us_id(user.getUs_id());
				temp.setAtl_type(at_type);
				temp.setAtl_up(atl_up);
				temp.setCompanyid(user.getCompanyid());
				temps_add.add(temp);
			}
		}
		if (temps_add.size() > 0) {
			allotDAO.temp_save(temps_add);
		}
		if (temps_update.size() > 0) {
			allotDAO.temp_updateById(temps_update);
		}
	}
	
	@Override
	@Transactional
	public void temp_copy(Map<String, Object> params) {
		String ids = (String)params.get("ids");
		Integer atl_up = (Integer)params.get("atl_up");
		Integer at_type = (Integer)params.get("at_type");
		T_Sys_User user = (T_Sys_User)params.get("user");
		if(StringUtil.isEmpty(ids)){
			throw new IllegalArgumentException("参数ids不能为null");
		}
		List<Long> atl_ids = new ArrayList<Long>();
		String[] idArr = ids.split(",");
		for (String id : idArr) {
			atl_ids.add(Long.parseLong(id));
		}
		List<T_Sort_AllotList> details = allotDAO.detail_list_forcopy(atl_ids);
		if (details == null || details.size() == 0) {
			throw new RuntimeException("单据明细不存在");
		}
		for(T_Sort_AllotList item:details){
			item.setAtl_us_id(user.getUs_id());
			item.setAtl_type(at_type);
			item.setAtl_up(atl_up);
			if(item.getAtl_sendamount().intValue() != 0){
				item.setAtl_applyamount(item.getAtl_sendamount());
			}
		}
		allotDAO.temp_clear(at_type,atl_up, user.getUs_id(), user.getCompanyid());
		allotDAO.temp_save(details);
	}
	
	@Override
	@Transactional
	public void temp_updateAmount(T_Sort_AllotList temp) {
		allotDAO.temp_update(temp);
	}
	
	@Override
	@Transactional
	public void temp_updatePrice(T_Sort_AllotList temp) {
		allotDAO.temp_updateprice(temp.getAtl_pd_code(), temp.getAtl_unitprice(), temp.getAtl_type(),temp.getAtl_up(),temp.getAtl_us_id(), temp.getCompanyid());
	}
	
	@Override
	@Transactional
	public void temp_updateRemarkById(T_Sort_AllotList temp) {
		allotDAO.temp_updateRemarkById(temp);
	}
	
	@Override
	@Transactional
	public void temp_updateRemarkByPdCode(T_Sort_AllotList temp) {
		allotDAO.temp_updateRemarkByPdCode(temp);
	}
	
	@Override
	@Transactional
	public void temp_del(Integer sel_id) {
		allotDAO.temp_del(sel_id);
	}

	@Override
	@Transactional
	public void temp_delByPiCode(T_Sort_AllotList temp) {
		if (temp.getCompanyid() == null) {
			throw new IllegalArgumentException("连接超时，请重新登录!");
		}
		if (temp.getAtl_us_id() == null) {
			throw new IllegalArgumentException("参数us_id不能为null");
		}
		if (temp.getAtl_type() == null) {
			throw new IllegalArgumentException("参数atl_type不能为null");
		}
		allotDAO.temp_delByPiCode(temp);
	}
	
	@Override
	@Transactional
	public void temp_clear(Integer at_type,Integer atl_up,Integer us_id,Integer companyid) {
		allotDAO.temp_clear(at_type, atl_up, us_id, companyid);
	}
	
	@Override
	@Transactional
	public void detail_updateAmount(T_Sort_AllotList temp) {
		allotDAO.detail_update(temp);
	}
	
	@Override
	@Transactional
	public void detail_automatch(String number,Integer companyid) {
		allotDAO.detail_automatch(number, companyid);
	}
	
	@Override
	@Transactional
	public void detail_del(Integer atl_id) {
		allotDAO.detail_del(atl_id);
	}
	
	@Override
	@Transactional
	public void save(T_Sort_Allot allot, T_Sys_User user,Integer atl_up) {
		if(StringUtil.isEmpty(allot.getAt_shop_code())){
			throw new IllegalArgumentException("店铺不能为空");
		}
		if(StringUtil.isEmpty(allot.getAt_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		String depot_type = "";
		if(user.getShoptype().equals("1") || (user.getShoptype().equals("2") && atl_up.intValue() == 0)){
			if(allot.getAt_type().intValue() == 0){
				depot_type = "out";
			}else {
				depot_type = "in";
			}
		}else {
			if(allot.getAt_type().intValue() == 0){
				depot_type = "in";
			}else {
				depot_type = "out";
			}
		}
		if("out".equals(depot_type)){
			if(StringUtil.isEmpty(allot.getAt_outdp_code())){
				throw new IllegalArgumentException("发货仓库不能为空");
			}
		}else if("in".equals(depot_type)){
			if(StringUtil.isEmpty(allot.getAt_indp_code())){
				throw new IllegalArgumentException("收货仓库不能为空");
			}
		}
		allot.setCompanyid(user.getCompanyid());
		allot.setAt_us_id(user.getUs_id());
		allot.setAt_maker(user.getUs_name());
		allot.setAt_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		allot.setAt_sysdate(DateUtil.getCurrentTime());
		allot.setAt_pay_state(0);
		
		//1.查临时表
		List<T_Sort_AllotList> temps = allotDAO.temp_list_forsave(allot.getAt_type(),atl_up, user.getUs_id(), user.getCompanyid());
		if(temps == null || temps.size() == 0){
			throw new RuntimeException("单据已保存，请勿重复提交");
		}
		//2.保存单据
		if(allot.getAt_type().equals(1)){//退货
			for (T_Sort_AllotList temp : temps) {
				temp.setAtl_applyamount(-Math.abs(temp.getAtl_applyamount()));
				temp.setAtl_sendamount(0);
			}
		}else{
			if(CommonUtil.ONE.equals(user.getShoptype()) || (CommonUtil.TWO.equals(user.getShoptype()) && atl_up.intValue() == 0)){//配货发货单(总公司、分公司)
				for (T_Sort_AllotList temp : temps) {
					temp.setAtl_sendamount(temp.getAtl_applyamount());
					temp.setAtl_applyamount(0);
				}
			}else {//补货申请单
				for (T_Sort_AllotList temp : temps) {
					temp.setAtl_sendamount(0);
				}
			}
		}
		int at_applyamount = 0;
		int at_sendamount = 0;
		double at_applymoney = 0d;
		double at_sendmoney = 0d;
		double at_sendcostmoney = 0d;
		double at_sendsellmoney = 0d;
		for (T_Sort_AllotList temp : temps) {
			at_applyamount += temp.getAtl_applyamount();
			at_sendamount += temp.getAtl_sendamount();
			at_applymoney += temp.getAtl_applyamount() * temp.getAtl_unitprice();
			at_sendmoney += temp.getAtl_sendamount() * temp.getAtl_unitprice();
			at_sendcostmoney += temp.getAtl_sendamount() * temp.getAtl_costprice();
			at_sendsellmoney += temp.getAtl_sendamount() * temp.getAtl_sellprice();
		}
		allot.setAt_applyamount(at_applyamount);
		allot.setAt_sendamount(at_sendamount);
		allot.setAt_applymoney(at_applymoney);
		allot.setAt_sendmoney(at_sendmoney);
		allot.setAt_sendcostmoney(at_sendcostmoney);
		allot.setAt_sendsellmoney(at_sendsellmoney);
		allot.setAt_discount_money(allot.getAt_discount_money() == null ? 0d : allot.getAt_discount_money());
		allot.setAt_receivable(allot.getAt_sendmoney()-allot.getAt_discount_money());
		allot.setAt_received(0d);
		allot.setAt_prepay(0d);
		allotDAO.save(allot,atl_up, temps,user);
		//3.删除临时表
		allotDAO.temp_clear(allot.getAt_type(),atl_up, user.getUs_id(), user.getCompanyid());
	}
	
	@Override
	@Transactional
	public void update(T_Sort_Allot allot, T_Sys_User user,Integer atl_up) {
		if(StringUtil.isEmpty(allot.getAt_shop_code())){
			throw new IllegalArgumentException("店铺不能为空");
		}
		if(StringUtil.isEmpty(allot.getAt_manager())){
			throw new IllegalArgumentException("经办人不能为空");
		}
		String depot_type = "";
		if(user.getShoptype().equals("1") || (user.getShoptype().equals("2") && atl_up.intValue() == 0)){
			if(allot.getAt_type().intValue() == 0){
				depot_type = "out";
			}else {
				depot_type = "in";
			}
		}else {
			if(allot.getAt_type().intValue() == 0){
				depot_type = "in";
			}else {
				depot_type = "out";
			}
		}
		if("out".equals(depot_type)){
			if(StringUtil.isEmpty(allot.getAt_outdp_code())){
				throw new IllegalArgumentException("发货仓库不能为空");
			}
		}else if("in".equals(depot_type)){
			if(StringUtil.isEmpty(allot.getAt_indp_code())){
				throw new IllegalArgumentException("收货仓库不能为空");
			}
		}
		allot.setCompanyid(user.getCompanyid());
		allot.setAt_us_id(user.getUs_id());
		allot.setAt_maker(user.getUs_name());
		allot.setAt_ar_state(CommonUtil.AR_STATE_NOTAPPROVE);
		allot.setAt_sysdate(DateUtil.getCurrentTime());
		allot.setAt_pay_state(0);
		
		//1.1查临时表
		List<T_Sort_AllotList> temps = allotDAO.temp_list_forsave(allot.getAt_type(),atl_up, user.getUs_id(), user.getCompanyid());
		if(temps == null || temps.size() == 0){
			throw new RuntimeException("单据已保存，请勿重复提交");
		}
		//1.2验证单据
		T_Sort_Allot oldAllot = allotDAO.check(allot.getAt_number(), user.getCompanyid());
		if (oldAllot == null || !CommonUtil.AR_STATE_FAIL.equals(oldAllot.getAt_ar_state())) {
			throw new RuntimeException("单据已修改，请勿重复提交");
		}
		//1.3删除子表
		allotDAO.deleteList(allot.getAt_number(), user.getCompanyid());
		//2.保存单据
		
		if(allot.getAt_type().equals(1)){//退货
			for (T_Sort_AllotList temp : temps) {
				temp.setAtl_applyamount(-Math.abs(temp.getAtl_applyamount()));
				temp.setAtl_sendamount(0);
			}
		}else{
			if(CommonUtil.ONE.equals(user.getShoptype()) || (CommonUtil.TWO.equals(user.getShoptype()) && atl_up.intValue() == 0)){//配货发货单(总公司、分公司)
				for (T_Sort_AllotList temp : temps) {
					temp.setAtl_sendamount(temp.getAtl_applyamount());
					temp.setAtl_applyamount(0);
				}
			}else {//补货申请单
				for (T_Sort_AllotList temp : temps) {
					temp.setAtl_sendamount(0);
				}
			}
		}
		int at_applyamount = 0;
		int at_sendamount = 0;
		double at_applymoney = 0d;
		double at_sendmoney = 0d;
		double at_sendcostmoney = 0d;
		double at_sendsellmoney = 0d;
		for (T_Sort_AllotList temp : temps) {
			at_applyamount += temp.getAtl_applyamount();
			at_sendamount += temp.getAtl_sendamount();
			at_applymoney += temp.getAtl_applyamount() * temp.getAtl_unitprice();
			at_sendmoney += temp.getAtl_sendamount() * temp.getAtl_unitprice();
			at_sendcostmoney += temp.getAtl_sendamount() * temp.getAtl_costprice();
			at_sendsellmoney += temp.getAtl_sendamount() * temp.getAtl_sellprice();
		}
		allot.setAt_applyamount(at_applyamount);
		allot.setAt_sendamount(at_sendamount);
		allot.setAt_applymoney(at_applymoney);
		allot.setAt_sendmoney(at_sendmoney);
		allot.setAt_sendcostmoney(at_sendcostmoney);
		allot.setAt_sendsellmoney(at_sendsellmoney);
		allot.setAt_discount_money(allot.getAt_discount_money() == null ? 0d : allot.getAt_discount_money());
		allot.setAt_receivable(allot.getAt_sendmoney()-allot.getAt_discount_money());
		allot.setAt_received(0d);
		allot.setAt_prepay(0d);
		allotDAO.update(allot, temps);
		//3.删除临时表
		allotDAO.temp_clear(allot.getAt_type(),atl_up, user.getUs_id(), user.getCompanyid());
	}
	
	@Override
	@Transactional
	public T_Sort_Allot approve(String number, T_Approve_Record record, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Sort_Allot allot = allotDAO.check(number, user.getCompanyid());
		if(allot == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.WANT_AR_STATE_NOTAPPROVE.equals(allot.getAt_ar_state())){
			throw new RuntimeException("单据已经审核");
		}
		if(CommonUtil.WANT_AR_STATE_APPROVED.equals(record.getAr_state()) && allot.getAt_applyamount().equals(0)){//店铺发货单审核通过
			if(StringUtil.isEmpty(allot.getAt_outdp_code())){
				throw new RuntimeException("发货仓库不能为空");
			}
		}
		//更新单据审核状态
		if(CommonUtil.WANT_AR_STATE_FAIL.equals(record.getAr_state())){
			allot.setAt_ar_state(record.getAr_state());
		}else if(allot.getAt_applyamount().equals(0)){//配货发货单
			allot.setAt_ar_state(CommonUtil.WANT_AR_STATE_SEND);
		}else {
			allot.setAt_ar_state(record.getAr_state());
		}
		allot.setAt_ar_date(DateUtil.getCurrentTime());
		allotDAO.updateApprove(allot);
		//保存审核记录表
		record.setAr_number(number);
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_sort_allot");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		if(CommonUtil.WANT_AR_STATE_FAIL.equals(allot.getAt_ar_state())){//审核不通过，则直接返回
			return allot;
		}
		if(allot.getAt_applyamount() != 0){
			return allot;
		}
		//3.审核通过(配货发货单直接发货)
		List<T_Stock_DataBill> stocks = allotDAO.listStock(number, allot.getAt_outdp_code(), user.getCompanyid());
		List<T_Stock_DataBill> add_stocks = new ArrayList<T_Stock_DataBill>();
		List<T_Stock_DataBill> update_stocks = new ArrayList<T_Stock_DataBill>();
		for (T_Stock_DataBill stock : stocks) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(allot.getAt_outdp_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				stock.setSd_amount(-stock.getBill_amount());
				add_stocks.add(stock);
			}else {
				stock.setSd_amount(stock.getSd_amount() - stock.getBill_amount());
				update_stocks.add(stock);
			}
		}
		if (add_stocks.size() > 0) {
			dataDAO.save(add_stocks);
		}
		if (update_stocks.size() > 0) {
			dataDAO.update(update_stocks);
		}
		//生成财务账目
		T_Base_Shop shop = shopDAO.loadShop(allot.getAt_shop_code(), user.getCompanyid());
		if(shop != null){
			shop.setSp_receivable(shop.getSp_receivable()+allot.getAt_receivable());
			shopDAO.updateReceivable(shop);
			T_Sort_Dealings dealings = new T_Sort_Dealings();
			dealings.setDl_shop_code(allot.getAt_shop_code());
			dealings.setDl_number(allot.getAt_number());
			dealings.setDl_type(allot.getAt_type());
			dealings.setDl_discount_money(allot.getAt_discount_money());
			dealings.setDl_receivable(allot.getAt_receivable());
			dealings.setDl_received(0d);
			dealings.setDl_debt(shop.getSp_receivable()-shop.getSp_received()-shop.getSp_prepay());
			dealings.setDl_date(DateUtil.getCurrentTime());
			dealings.setDl_manager(user.getUs_name());
			dealings.setDl_remark(allot.getAt_remark());
			dealings.setDl_sysdate(DateUtil.getCurrentTime());
			dealings.setDl_amount(allot.getAt_sendamount());
			dealings.setCompanyid(user.getCompanyid());
			sortDealingsDAO.save(dealings);
		}
		return allot;
	}
	
	@Override
	@Transactional
	public T_Sort_Allot send(String number, String at_outdp_code, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Sort_Allot allot = allotDAO.check(number, user.getCompanyid());
		if(allot == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.WANT_AR_STATE_APPROVED.equals(allot.getAt_ar_state())){
			throw new RuntimeException("单据未审核或已发货");
		}
		allot.setAt_outdp_code(at_outdp_code);
		allot.setAt_ar_state(CommonUtil.WANT_AR_STATE_SEND);
		if(StringUtil.isEmpty(allot.getAt_outdp_code())){
			throw new RuntimeException("发货仓库不能为空");
		}
		allotDAO.updateSend(allot);
		//保存审核记录表
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_SEND);
		record.setAr_number(number);
		record.setAr_describe("");
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_sort_allot");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		//3.发货
		List<T_Stock_DataBill> stocks = allotDAO.listStock(number, allot.getAt_outdp_code(), user.getCompanyid());
		List<T_Stock_DataBill> add_stocks = new ArrayList<T_Stock_DataBill>();
		List<T_Stock_DataBill> update_stocks = new ArrayList<T_Stock_DataBill>();
		for (T_Stock_DataBill stock : stocks) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(allot.getAt_outdp_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				stock.setSd_amount(-stock.getBill_amount());
				add_stocks.add(stock);
			}else {
				stock.setSd_amount(stock.getSd_amount() - stock.getBill_amount());
				update_stocks.add(stock);
			}
		}
		if (add_stocks.size() > 0) {
			dataDAO.save(add_stocks);
		}
		if (update_stocks.size() > 0) {
			dataDAO.update(update_stocks);
		}
		if(allot.getAt_type().equals(0)){//生成财务账目
			T_Base_Shop shop = shopDAO.loadShop(allot.getAt_shop_code(), user.getCompanyid());
			if(shop != null){
				shop.setSp_receivable(shop.getSp_receivable()+allot.getAt_receivable());
				shopDAO.updateReceivable(shop);
				T_Sort_Dealings dealings = new T_Sort_Dealings();
				dealings.setDl_shop_code(allot.getAt_shop_code());
				dealings.setDl_number(allot.getAt_number());
				dealings.setDl_type(allot.getAt_type());
				dealings.setDl_discount_money(allot.getAt_discount_money());
				dealings.setDl_receivable(allot.getAt_receivable());
				dealings.setDl_received(0d);
				dealings.setDl_debt(shop.getSp_receivable()-shop.getSp_received()-shop.getSp_prepay());
				dealings.setDl_date(DateUtil.getCurrentTime());
				dealings.setDl_manager(user.getUs_name());
				dealings.setDl_remark(allot.getAt_remark());
				dealings.setDl_sysdate(DateUtil.getCurrentTime());
				dealings.setDl_amount(allot.getAt_sendamount());
				dealings.setCompanyid(user.getCompanyid());
				sortDealingsDAO.save(dealings);
			}
		}
		return allot;
	}
	
	@Override
	@Transactional
	public T_Sort_Allot receive(String number, String at_indp_code, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Sort_Allot allot = allotDAO.check(number, user.getCompanyid());
		if(allot == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.WANT_AR_STATE_SEND.equals(allot.getAt_ar_state())){
			throw new RuntimeException("单据未发货或已完成");
		}
		allot.setAt_indp_code(at_indp_code);
		allot.setAt_ar_state(CommonUtil.WANT_AR_STATE_FINISH);
		if(StringUtil.isEmpty(allot.getAt_indp_code())){
			throw new RuntimeException("收货仓库不能为空");
		}
		allotDAO.updateReceive(allot);
		//保存审核记录表
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_FINISH);
		record.setAr_number(number);
		record.setAr_describe("");
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_sort_allot");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		//3.收货
		List<T_Stock_DataBill> stocks = allotDAO.listStock(number, allot.getAt_indp_code(), user.getCompanyid());
		List<T_Stock_DataBill> add_stocks = new ArrayList<T_Stock_DataBill>();
		List<T_Stock_DataBill> update_stocks = new ArrayList<T_Stock_DataBill>();
		for (T_Stock_DataBill stock : stocks) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(allot.getAt_indp_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				stock.setSd_amount(stock.getBill_amount());
				add_stocks.add(stock);
			}else {
				stock.setSd_amount(stock.getSd_amount() + stock.getBill_amount());
				update_stocks.add(stock);
			}
		}
		if (add_stocks.size() > 0) {
			dataDAO.save(add_stocks);
		}
		if (update_stocks.size() > 0) {
			dataDAO.update(update_stocks);
		}
		if(allot.getAt_type().equals(1)){//生成财务账目
			T_Base_Shop shop = shopDAO.loadShop(allot.getAt_shop_code(), user.getCompanyid());
			if(shop != null){
				shop.setSp_receivable(shop.getSp_receivable()+allot.getAt_receivable());
				shopDAO.updateReceivable(shop);
				T_Sort_Dealings dealings = new T_Sort_Dealings();
				dealings.setDl_shop_code(allot.getAt_shop_code());
				dealings.setDl_number(allot.getAt_number());
				dealings.setDl_type(allot.getAt_type());
				dealings.setDl_discount_money(allot.getAt_discount_money());
				dealings.setDl_receivable(allot.getAt_receivable());
				dealings.setDl_received(0d);
				dealings.setDl_debt(shop.getSp_receivable()-shop.getSp_received()-shop.getSp_prepay());
				dealings.setDl_date(DateUtil.getCurrentTime());
				dealings.setDl_manager(user.getUs_name());
				dealings.setDl_remark(allot.getAt_remark());
				dealings.setDl_sysdate(DateUtil.getCurrentTime());
				dealings.setDl_amount(allot.getAt_sendamount());
				dealings.setCompanyid(user.getCompanyid());
				sortDealingsDAO.save(dealings);
			}
		}
		if(allot.getAt_type().equals(0)){//更新分店价格
			List<ProductStorePriceDto> priceDtos = allotDAO.load_allot_product_price(number, allot.getAt_shop_code(), user.getCompanyid());
			//查询库存数量用于加权平均
			List<T_Stock_DataBill> stockAmounts = allotDAO.listStockAmount(number, allot.getAt_shop_code(), user.getCompanyid());
			Map<String, Integer> stockAmountMap = new HashMap<String, Integer>();
			for (T_Stock_DataBill stockAmount : stockAmounts) {
				stockAmountMap.put(stockAmount.getSd_pd_code(), stockAmount.getSd_amount());
			}
			List<T_Base_Product_Shop_Price> shopPrices_add = new ArrayList<T_Base_Product_Shop_Price>();
			List<T_Base_Product_Shop_Price> shopPrices_update = new ArrayList<T_Base_Product_Shop_Price>();
			for (ProductStorePriceDto dto : priceDtos) {
				if (dto.getPdp_id() != null && dto.getPdp_id().intValue() != 0) {//分店价格已存在
					if(!dto.getUnitprice().equals(dto.getPdp_sort_price())){
						T_Base_Product_Shop_Price shop_Price = new T_Base_Product_Shop_Price();
						shop_Price.setPdp_id(dto.getPdp_id());
						int stock = 0;
						if(stockAmountMap.containsKey(dto.getPd_code())){
							stock = stockAmountMap.get(dto.getPd_code());
						}
						double costPrice = dto.getUnitprice();
						if (stock + dto.getAmount() != 0) {
							costPrice = (dto.getPdp_cost_price() * stock + dto.getUnitprice() * dto.getAmount())
									/ (stock + dto.getAmount());
						}
						shop_Price.setPdp_sort_price(dto.getUnitprice());
						shop_Price.setPdp_cost_price(costPrice);
						shopPrices_update.add(shop_Price);
					}
				}else {//分店价格不存在
					T_Base_Product_Shop_Price shop_Price = new T_Base_Product_Shop_Price();
					shop_Price.setPdp_pd_code(dto.getPd_code());
					shop_Price.setPdp_shop_code(allot.getAt_shop_code());
					shop_Price.setCompanyid(user.getCompanyid());
					shop_Price.setPdp_sell_price(dto.getPd_sell_price());
					shop_Price.setPdp_vip_price(dto.getPd_vip_price());
					shop_Price.setPdp_cost_price(dto.getUnitprice());
					shop_Price.setPdp_sort_price(dto.getUnitprice());
					shopPrices_add.add(shop_Price);
				}
			}
			if (shopPrices_add.size() > 0 || shopPrices_update.size() > 0) {
				allotDAO.update_base_shopprice(shopPrices_add, shopPrices_update);
			}
		}
		return allot;
	}
	
	@Override
	@Transactional
	public T_Sort_Allot reject(String number, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Sort_Allot allot = allotDAO.check(number, user.getCompanyid());
		if(allot == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.WANT_AR_STATE_SEND.equals(allot.getAt_ar_state())){
			throw new RuntimeException("单据未发货或已完成");
		}
		allot.setAt_ar_state(CommonUtil.WANT_AR_STATE_REJECT);
		allotDAO.updateReject(allot);
		//保存审核记录表
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_REJECT);
		record.setAr_number(number);
		record.setAr_describe("");
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_sort_allot");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		return allot;
	}
	
	@Override
	@Transactional
	public T_Sort_Allot rejectconfirm(String number, T_Sys_User user) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Sort_Allot allot = allotDAO.check(number, user.getCompanyid());
		if(allot == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.WANT_AR_STATE_REJECT.equals(allot.getAt_ar_state())){
			throw new RuntimeException("单据未被拒收，不能确认");
		}
		T_Sort_Allot confirmAllot = new T_Sort_Allot();
		confirmAllot.setAt_id(allot.getAt_id());
		confirmAllot.setAt_ar_state(CommonUtil.WANT_AR_STATE_APPROVED);
		confirmAllot.setAt_sendamount(0);
		confirmAllot.setAt_sendmoney(0d);
		confirmAllot.setAt_sendcostmoney(0d);
		confirmAllot.setAt_sendsellmoney(0d);
		confirmAllot.setAt_receivable(0d);
		allotDAO.updateRejectConfirm(confirmAllot);
		//保存审核记录表
		T_Approve_Record record = new T_Approve_Record();
		record.setAr_state(CommonUtil.AR_STATE_REJECTCONFIRM);
		record.setAr_number(number);
		record.setAr_describe("");
		record.setAr_sysdate(DateUtil.getCurrentTime());
		record.setAr_us_name(user.getUs_name());
		record.setAr_type("t_sort_allot");
		record.setCompanyid(user.getCompanyid());
		approveRecordDAO.save(record);
		
		//3.恢复库存
		List<T_Stock_DataBill> stocks = allotDAO.listStock(number, allot.getAt_outdp_code(), user.getCompanyid());
		List<T_Stock_DataBill> add_stocks = new ArrayList<T_Stock_DataBill>();
		List<T_Stock_DataBill> update_stocks = new ArrayList<T_Stock_DataBill>();
		for (T_Stock_DataBill stock : stocks) {
			if(stock.getSd_id() == null){
				stock.setSd_dp_code(allot.getAt_outdp_code());
				stock.setSd_init(0);
				stock.setSd_date(DateUtil.getCurrentTime());
				stock.setCompanyid(user.getCompanyid());
				stock.setSd_amount(stock.getBill_amount());
				add_stocks.add(stock);
			}else {
				stock.setSd_amount(stock.getSd_amount() + stock.getBill_amount());
				update_stocks.add(stock);
			}
		}
		if (add_stocks.size() > 0) {
			dataDAO.save(add_stocks);
		}
		if (update_stocks.size() > 0) {
			dataDAO.update(update_stocks);
		}
		if(allot.getAt_type().equals(0)){//恢复财务账目
			T_Base_Shop shop = shopDAO.loadShop(allot.getAt_shop_code(), user.getCompanyid());
			if(shop != null){
				shop.setSp_receivable(shop.getSp_receivable()-allot.getAt_receivable());
				shopDAO.updateReceivable(shop);
				T_Sort_Dealings dealings = new T_Sort_Dealings();
				dealings.setDl_shop_code(allot.getAt_shop_code());
				dealings.setDl_number(allot.getAt_number());
				dealings.setDl_type(allot.getAt_type());
				dealings.setDl_discount_money(-allot.getAt_discount_money());
				dealings.setDl_receivable(-allot.getAt_receivable());
				dealings.setDl_received(0d);
				dealings.setDl_debt(shop.getSp_receivable()-shop.getSp_received()-shop.getSp_prepay());
				dealings.setDl_date(DateUtil.getCurrentTime());
				dealings.setDl_manager(user.getUs_name());
				dealings.setDl_remark("拒收确认恢复账目往来明细");
				dealings.setDl_sysdate(DateUtil.getCurrentTime());
				dealings.setDl_amount(-allot.getAt_sendamount());
				dealings.setCompanyid(user.getCompanyid());
				sortDealingsDAO.save(dealings);
			}
		}
		allot.setAt_ar_state(CommonUtil.WANT_AR_STATE_APPROVED);
		allot.setAt_sendamount(0);
		allot.setAt_sendmoney(0d);
		allot.setAt_sendcostmoney(0d);
		allot.setAt_sendsellmoney(0d);
		allot.setAt_receivable(0d);
		return allot;
	}
	
	@Override
	@Transactional
	public void initUpdate(String number,Integer at_type,Integer atl_up, Integer us_id, Integer companyid) {
		List<T_Sort_AllotList> details = allotDAO.detail_list_forsavetemp(number, companyid);;
		for(T_Sort_AllotList item:details){
			item.setAtl_us_id(us_id);
			item.setAtl_up(atl_up);
			if(item.getAtl_applyamount().intValue() == 0){
				item.setAtl_applyamount(item.getAtl_sendamount());
			}
		}
		allotDAO.temp_clear(at_type,atl_up, us_id, companyid);
		allotDAO.temp_save(details);
	}
	
	@Override
	@Transactional
	public void del(String number, Integer companyid) {
		if (number == null) {
			throw new IllegalArgumentException("参数number不能为null");
		}
		T_Sort_Allot allot = allotDAO.check(number, companyid);
		if(allot == null){
			throw new RuntimeException("单据不存在");
		}
		if(!CommonUtil.AR_STATE_NOTAPPROVE.equals(allot.getAt_ar_state()) && !CommonUtil.AR_STATE_FAIL.equals(allot.getAt_ar_state())){
			throw new RuntimeException("单据已审核通过不能删除！");
		}
		allotDAO.del(number, companyid);
	}
	
	@Override
	public Map<String, Object> loadPrintData(String number, Integer sp_id, Integer displayMode,T_Sys_User user) {
		Map<String, Object> resultMap = printDAO.loadPrint4Bill(sp_id);
		T_Sort_Allot allot = allotDAO.load(number, user.getCompanyid());
		List<T_Sort_AllotList> allotList = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("atl_number", number);
		params.put("companyid", user.getCompanyid());
		if(displayMode.intValue() == 2){//汇总模式
			allotList = allotDAO.detail_sum(params);
		}else if(displayMode.intValue() == 1){//尺码模式 
			params.put(CommonUtil.SIDX, "atl_pd_code,atl_cr_code,atl_br_code");
			params.put(CommonUtil.SORD, "ASC");
			allotList = allotDAO.detail_list_print(params);
		}else {
			allotList = allotDAO.detail_list_print(params);
		}
		resultMap.put("allot", allot);
		resultMap.put("allotList", allotList);
		resultMap.put("shop", shopDAO.load(allot.getAt_shop_code(), user.getCompanyid()));
		if(displayMode.intValue() == 1){//尺码模式查询
			List<String> szgCodes = new ArrayList<String>();
			for (T_Sort_AllotList item : allotList) {
				if(!szgCodes.contains(item.getAtl_szg_code())){
					szgCodes.add(item.getAtl_szg_code());
				}
			}
			List<T_Base_SizeList> sizeGroupList = sizeDAO.listBySzg(szgCodes, user.getCompanyid());
			resultMap.put("sizeGroupList", sizeGroupList);
		}
		return resultMap;
	}
	
}
